<template>
  <div class="media-controls">
    <div class="button-group">
      <MediaButton 
        type="audio" 
        :active="audioActive" 
        @click="toggleAudio"
        icon="microphone"
        label="语音"
      />
      
      <MediaButton 
        type="video" 
        :active="videoActive" 
        @click="toggleVideo"
        icon="video"
        label="视频"
      />
      
      <MediaButton 
        type="screen" 
        :active="screenActive" 
        @click="toggleScreen"
        icon="desktop"
        label="屏幕共享"
      />
    </div>
    
    <div class="stream-preview">
      <AudioStream v-if="audioActive" :stream="audioStream" />
      <VideoStream v-if="videoActive" :stream="videoStream" />
      <ScreenShare v-if="screenActive" :stream="screenStream" />
    </div>
    
    <div class="status-bar">
      <StatusIndicator :status="connectionStatus" />
      <div class="connection-info">
        <span v-if="connectionStatus === 'connected'">
          已连接 - {{ participants }} 人参与
        </span>
        <span v-else>准备中...</span>
      </div>
    </div>
    
    <div class="error-message" v-if="errorMessage">
      <i class="fas fa-exclamation-triangle"></i> {{ errorMessage }}
      <button class="retry-btn" @click="retryConnection" v-if="connectionStatus === 'failed'">
        <i class="fas fa-redo"></i> 重试连接
      </button>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import MediaButton from './MediaButton.vue';
import AudioStream from './AudioStream.vue';
import VideoStream from './VideoStream.vue';
import ScreenShare from './ScreenShare.vue';
import StatusIndicator from './StatusIndicator.vue';
import { 
  requestMicrophone, 
  requestCamera, 
  requestScreenSharing,
  releaseMediaResources
} from '../utils/mediaUtils';
import DingRTCWrapper from '../utils/dingrtc-wrapper';

export default {
  components: {
    MediaButton,
    AudioStream,
    VideoStream,
    ScreenShare,
    StatusIndicator
  },
  
  setup() {
    const audioStream = ref(null);
    const videoStream = ref(null);
    const screenStream = ref(null);
    const participants = ref(0);
    const connectionStatus = ref('disconnected');
    const errorMessage = ref('');
    const dingRTC = ref(null);
    
    // 阿里云DingRTC配置
    const appId = 'a4zfr1hn'; // 替换为你的AppID
    const userId = `user_${Math.floor(Math.random() * 10000)}`;
    const channel = 'default_channel';
    
    // 从服务器获取Token的函数（需要实现）
    const fetchToken = async () => {
      // 实际项目中应从服务器获取Token
      // 这里使用模拟Token
      return '000eJxjYGBQaJCODF7Yu/LHO5Gy41uUS1M5s5b+83R/UMlpprzL5MIvXQYGBo68vKTs1Mqi8gyLGIcrWaGbMizX7geK8xoam+saGliY6hoZGJphCjAyjIJBDQDLqh2m';
    };
    
    const audioActive = computed(() => !!audioStream.value);
    const videoActive = computed(() => !!videoStream.value);
    const screenActive = computed(() => !!screenStream.value);
    
    // 初始化DingRTC连接
    const initConnection = async () => {
      try {
        errorMessage.value = '';
        connectionStatus.value = 'connecting';
        
        // 从服务器获取Token
        const token = await fetchToken();
        
        dingRTC.value = new DingRTCWrapper();
        
        // 设置事件监听
        dingRTC.value.on('connection-state-change', (state) => {
          connectionStatus.value = state;
        });
        
        dingRTC.value.on('stream-added', (stream) => {
          // 自动订阅新流
          dingRTC.value.subscribe(stream);
        });
        
        dingRTC.value.on('stream-subscribed', (stream) => {
          // 更新参与者数量
          participants.value = dingRTC.value.getParticipantCount();
        });
        
        dingRTC.value.on('stream-removed', () => {
          participants.value = dingRTC.value.getParticipantCount();
        });
        
        dingRTC.value.on('error', (error) => {
          console.error('DingRTC错误:', error);
          errorMessage.value = `连接错误: ${error.message}`;
        });
        
        // 初始化连接
        await dingRTC.value.initialize(appId, userId, channel, token);
        
        connectionStatus.value = 'connected';
      } catch (error) {
        console.error('连接失败:', error);
        connectionStatus.value = 'failed';
        errorMessage.value = `连接失败: ${error.message}`;
      }
    };
    
    // 启动麦克风
    const startAudio = async () => {
      try {
        audioStream.value = await requestMicrophone();
        
        if (dingRTC.value) {
          await dingRTC.value.publish(audioStream.value, {
            audio: true,
            video: false,
            screen: false
          });
        }
      } catch (error) {
        console.error('启动麦克风失败:', error);
        errorMessage.value = handleMediaError(error);
        audioStream.value = null;
      }
    };
    
    // 停止麦克风
    const stopAudio = () => {
      if (audioStream.value) {
        releaseMediaResources(audioStream.value);
        audioStream.value = null;
        
        if (dingRTC.value) {
          dingRTC.value.unpublish();
        }
      }
    };
    
    // 启动摄像头
    const startVideo = async () => {
      try {
        videoStream.value = await requestCamera();
        
        if (dingRTC.value) {
          await dingRTC.value.publish(videoStream.value, {
            audio: false,
            video: true,
            screen: false
          });
        }
      } catch (error) {
        console.error('启动摄像头失败:', error);
        errorMessage.value = handleMediaError(error);
        videoStream.value = null;
      }
    };
    
    // 停止摄像头
    const stopVideo = () => {
      if (videoStream.value) {
        releaseMediaResources(videoStream.value);
        videoStream.value = null;
        
        if (dingRTC.value) {
          dingRTC.value.unpublish();
        }
      }
    };
    
    // 启动屏幕共享
    const startScreenSharing = async () => {
      try {
        screenStream.value = await requestScreenSharing();
        
        if (dingRTC.value) {
          await dingRTC.value.publish(screenStream.value, {
            audio: true,
            video: false,
            screen: true
          });
        }
      } catch (error) {
        console.error('启动屏幕共享失败:', error);
        errorMessage.value = handleMediaError(error);
        screenStream.value = null;
      }
    };
    
    // 停止屏幕共享
    const stopScreenSharing = () => {
      if (screenStream.value) {
        releaseMediaResources(screenStream.value);
        screenStream.value = null;
        
        if (dingRTC.value) {
          dingRTC.value.unpublish();
        }
      }
    };
    
    // 切换麦克风状态
    const toggleAudio = () => {
      if (audioActive.value) {
        stopAudio();
      } else {
        startAudio();
      }
    };
    
    // 切换摄像头状态
    const toggleVideo = () => {
      if (videoActive.value) {
        stopVideo();
      } else {
        startVideo();
      }
    };
    
    // 切换屏幕共享状态
    const toggleScreen = () => {
      if (screenActive.value) {
        stopScreenSharing();
      } else {
        startScreenSharing();
      }
    };
    
    // 处理媒体错误
    const handleMediaError = (error) => {
      switch (error.name) {
        case 'NotAllowedError':
          return '权限被拒绝：请允许浏览器访问您的媒体设备';
        case 'NotFoundError':
          return '未找到媒体设备：请检查您的摄像头和麦克风';
        case 'NotReadableError':
          return '设备被占用：请关闭其他使用媒体设备的应用';
        default:
          return `媒体操作失败：${error.message}`;
      }
    };
    
    // 重试连接
    const retryConnection = async () => {
      await initConnection();
    };
    
    // 组件挂载时初始化连接
    onMounted(() => {
      initConnection();
    });
    
    // 组件卸载时清理资源
    onBeforeUnmount(() => {
      if (dingRTC.value) {
        dingRTC.value.leave();
      }
      
      stopAudio();
      stopVideo();
      stopScreenSharing();
    });
    
    return {
      audioStream,
      videoStream,
      screenStream,
      participants,
      connectionStatus,
      errorMessage,
      audioActive,
      videoActive,
      screenActive,
      toggleAudio,
      toggleVideo,
      toggleScreen,
      retryConnection
    };
  }
};
</script>

<style scoped>
.media-controls {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: #1a1e2c;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.button-group {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.stream-preview {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-bottom: 20px;
  min-height: 200px;
  background: #0d1117;
  border-radius: 8px;
  padding: 10px;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #252a38;
  border-radius: 8px;
}

.connection-info {
  color: #a0aec0;
  font-size: 0.9rem;
}

.error-message {
  margin-top: 15px;
  padding: 12px;
  background: #e74c3c;
  color: white;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.retry-btn {
  margin-left: auto;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.retry-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

@media (max-width: 768px) {
  .button-group,
  .stream-preview {
    grid-template-columns: 1fr;
  }
  
  .stream-preview {
    grid-row-gap: 10px;
  }
}
</style>